package test;

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x){ val = x;}
}
public class Solution{
    private int maxSum = Integer.MIN_VALUE;
    public int maxPathSum(TreeNode root){
        maxGain(root);
        return maxSum;
    }

    private int maxGain(TreeNode node) {
        if (node == null) {
            return 0;
        }
        //计算左右子节点的最大贡献值
        int leftGain = Math.max(maxGain(node.left),0);
        int rightGain = Math.max(maxGain(node.right),0);
        int priceNewPath = node.val + leftGain + rightGain;
        //更新答案
        maxSum = Math.max(maxSum , priceNewPath);
        //返回节点的最大贡献值
        return node.val + Math.max(leftGain,rightGain);
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.right = new TreeNode(3);
        Solution solution = new Solution();
        System.out.println(solution.maxPathSum(root));
    }
}
